import pygame
import yaml

pygame.mixer.quit()
pygame.mixer.init(22050, 8, 2, 2048)

class SoundServer():
    
    def __init__(self):
        self.sounds = {}
        self.musicChannels = []
        self.effectChannels = []
        self.config = {}
        
        try:
            self.config = yaml.load(open("sound/soundConfig.yml"))
        except:
            print "Crap!!! Why is it broken???"

        count = 0
        if(self.config.has_key("musicChannels")):
            mc = self.config["musicChannels"]
        else:
            mc = 1
        if(self.config.has_key("effectChannels")):
            sc = self.config["effectChannels"]
        else:
            sc = 1
            
        self.channelTotal = mc + sc
        pygame.mixer.set_num_channels(self.channelTotal)
            
        for i in range(mc):
            self.musicChannels.append(pygame.mixer.Channel(count))
            count += 1
        for i in range(sc):
            self.effectChannels.append(pygame.mixer.Channel(count))
            count += 1
        
        if(self.config.has_key("music")):
            for k, v in self.config["music"].iteritems():
                v = v.split(", ")
                if(len(v) == 2):
                    self.add(k, "sound/" + v[0], False)
                    self.volume(k, eval(v[1]))
                else:
                    self.add(k, "sound/" + v[0], False)
        if(self.config.has_key("effect")):
            for k, v in self.config["effect"].iteritems():
                v = v.split(", ")
                if(len(v) == 2):
                    self.add(k, "sound/" + v[0])
                    self.volume(k, eval(v[1]))
                else:
                    self.add(k, "sound/" + v[0])
        
    def add(self, name, path, effect = True):
        self.sounds[name] = [pygame.mixer.Sound(path), effect]

    def play(self, name, loop = False):
        if(self.sounds.has_key(name)):
            sound  = self.sounds[name][0]
            effect = self.sounds[name][1]
            if(effect):
                q = self.effectChannels
            else:
                q = self.musicChannels
                
            channel  = q.pop()
            if(loop):
                channel.play(sound, -1)
            else:
                channel.play(sound, 0)
            q.append(channel)
            
    def stop(self, name):
        if(self.sounds.has_key(name)):
            sound = self.sounds[name][0]
            sound.stop()
                
    def volume(self, name, level):
        if(self.sounds.has_key(name)):
            sound = self.sounds[name][0]
            sound.set_volume(level)
            
sound = SoundServer()